<script setup lang="ts">
import {ref, watch} from "vue";
import {ElMessage} from "element-plus";
import {
  getAllProvince,
  getAllCities,
  getAllDistricts,
  addFamilyVO,
  addFamilyUser,
  updateFamilyInfo
} from "@/api/familyManagement/docFamily";

const props = defineProps({
  visible: Boolean,
  mode: {type: String, default: "create"}, // create | edit
  familyInfo: {type: Object, default: null}
});
const emit = defineEmits(["close", "reload"]);

const dialogVisible = ref(false);

watch(
    () => props.visible,
    (val) => {
      dialogVisible.value = val;
      if (val) {
        resetForm();
        initProvinces();
        if (props.mode === "edit" && props.familyInfo) {
          form.value.familyName = props.familyInfo.familyName || "";
          // 拆分地址回填
          if (props.familyInfo.familyAddress) {
            const parts = props.familyInfo.familyAddress.split(" ");
            form.value.provinceName = parts[0] || "";
            form.value.cityName = parts[1] || "";
            form.value.districtName = parts[2] || "";
            // form.value.detailAddress = parts.slice(3).join(" ") || "";
            form.value.detailAddress = ""; // 不回写
          }
        }
      }
    }
);

const form = ref({
  familyName: "",
  province: null,
  city: null,
  district: null,
  detailAddress: "",
  provinceName: "",
  cityName: "",
  districtName: ""
});

const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

// 重置表单
const resetForm = () => {
  form.value = {
    familyName: "",
    province: null,
    city: null,
    district: null,
    detailAddress: "",
    provinceName: "",
    cityName: "",
    districtName: ""
  };
  cities.value = [];
  districts.value = [];
};

// 初始化省份
const initProvinces = async () => {
  try {
    const res = await getAllProvince();
    provinces.value = Array.isArray(res) ? res : res.data || [];
  } catch (e) {
    console.error("获取省份失败", e);
    provinces.value = [];
  }
};

// 省份变化
const handleProvinceChange = async (provinceId) => {
  const province = provinces.value.find(p => p.id === provinceId);
  form.value.provinceName = province ? province.name : "";
  form.value.city = null;
  form.value.district = null;
  form.value.cityName = "";
  form.value.districtName = "";
  cities.value = [];
  districts.value = [];
  try {
    const res = await getAllCities(Number(provinceId));
    cities.value = Array.isArray(res) ? res : res.data || [];
  } catch (e) {
    console.error("获取城市失败", e);
  }
};

// 城市变化
const handleCityChange = async (cityId) => {
  const city = cities.value.find(c => c.id === cityId);
  form.value.cityName = city ? city.name : "";
  form.value.district = null;
  form.value.districtName = "";
  districts.value = [];
  try {
    const res = await getAllDistricts(Number(cityId));
    districts.value = Array.isArray(res) ? res : res.data || [];
  } catch (e) {
    console.error("获取区/县失败", e);
  }
};

// 区/县变化
const handleDistrictChange = (districtId) => {
  const district = districts.value.find(d => d.id === districtId);
  form.value.districtName = district ? district.name : "";
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  emit("close");
};

// 提交表单
const handleSave = async () => {
  if (!form.value.familyName) {
    ElMessage.warning("请填写家庭名称");
    return;
  }
  if (!form.value.provinceName || !form.value.cityName || !form.value.districtName || !form.value.detailAddress) {
    ElMessage.warning("请完整选择地址并填写详细地址");
    return;
  }

  const familyAddress = `${form.value.provinceName} ${form.value.cityName} ${form.value.districtName} ${form.value.detailAddress}`;

  try {
    if (props.mode === "create") {
      await addFamilyVO({
        familyName: form.value.familyName,
        familyAddress
      });
      await addFamilyUser();
      ElMessage.success("家庭创建成功");
    } else {
      await updateFamilyInfo({
        familyName: form.value.familyName,
        familyAddress
      });
      ElMessage.success("家庭信息修改成功");
    }
    emit("reload");
    handleClose();
  } catch (e) {
    console.error(props.mode === "create" ? "创建家庭失败" : "修改家庭失败", e);
    ElMessage.error(props.mode === "create" ? "创建失败" : "修改失败");
  }
};
</script>

<template>
  <el-dialog
      :title="props.mode === 'create' ? '创建家庭' : '修改家庭信息'"
      width="1000px"
      v-model="dialogVisible"
      @close="handleClose"
      :modal-append-to-body="false"
      custom-class="family-dialog"
  >
    <el-form :model="form" label-width="70px" class="family-form">
      <el-form-item label="家庭名称">
        <el-input v-model="form.familyName" placeholder="请输入家庭名称"/>
      </el-form-item>

      <div class="address-row">
        <div class="address-item">
          <el-form-item label="省">
            <el-select v-model="form.province" placeholder="请选择省" @change="handleProvinceChange" clearable>
              <el-option v-for="p in provinces" :key="p.id" :label="p.name" :value="p.id"/>
            </el-select>
          </el-form-item>
        </div>

        <div class="address-item">
          <el-form-item label="市">
            <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange" clearable>
              <el-option v-for="c in cities" :key="c.id" :label="c.name" :value="c.id"/>
            </el-select>
          </el-form-item>
        </div>

        <div class="address-item">
          <el-form-item label="区">
            <el-select v-model="form.district" placeholder="请选择区" @change="handleDistrictChange" clearable>
              <el-option v-for="d in districts" :key="d.id" :label="d.name" :value="d.id"/>
            </el-select>
          </el-form-item>
        </div>
      </div>

      <el-form-item label="详细地址">
        <el-input
            v-model="form.detailAddress"
            type="textarea"
            placeholder="请输入详细地址"
        />
      </el-form-item>

      <div class="form-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.family-form {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .el-form-item {
    margin-bottom: 18px;
    width: 100%;
  }

  .el-input,
  .el-select {
    width: 100%;
    border-radius: 6px;
    background-color: #f8f8f8;
  }

  .address-row {
    display: flex;
    flex-wrap: nowrap;
    gap: 0;
  }

  .address-item {
    flex: 1;
    min-width: 240px;
    margin-left: 0;
    margin-right: 0;

    .el-form-item__content {
      width: 100%;
    }
  }

  .form-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;

    .el-button {
      min-width: 100px;
      border-radius: 20px;
      padding: 10px 24px;
      font-weight: 500;

      &--primary {
        background: linear-gradient(135deg, #409EFF, #337ecc);
        border: none;
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.4);
      }
    }
  }

  @media (max-width: 768px) {
    .address-row {
      flex-direction: column;
    }

    .family-dialog.el-dialog {
      width: 95% !important;
    }
  }
}
</style>
